package com.nuanshui.heatedloan.extension.error;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.heatedloan.controller.ResponseObject;

/**
 * 错误处理类
 * @ClassName: ExceptionHandler 
 * @author guohao
 * @date 2015年4月14日 下午4:48:08 
 *
 */
@ControllerAdvice
class ExceptionHandler {

	Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 错误的具体处理方法
	 * @param 
	 * @author guohao
	 * @date 2015年4月14日 下午4:50:33
	 */
	@ResponseBody
	@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
	public String exception(HttpServletRequest req, Exception e) {
		log.error(req.getRequestURI()+" general error", e);

		GlobalErrorCode errorCode;
		String moreInfo;
		if (e instanceof MissingServletRequestParameterException) {
			errorCode = GlobalErrorCode.INVALID_ARGUMENT;
			RequestContext requestContext = new RequestContext(req);
			Object[] params = new Object[1];
			params[0] = ((MissingServletRequestParameterException) e).getParameterName();
			moreInfo = requestContext.getMessage("valid.notBlank.param", params);
		} else if (e instanceof SQLException) {
			errorCode = GlobalErrorCode.INTERNAL_ERROR;
			moreInfo = e.getClass().getName();
		}
		else {
			BizException bizException = getBizException(e);
			if (bizException != null) {
				errorCode = bizException.getErrorCode();
				moreInfo = bizException.getMessage();

			} else {
				errorCode = GlobalErrorCode.UNKNOWN;
				moreInfo = "系统异常请稍后再试";
			}
		}

		ResponseObject<Object>  responseObject  = new ResponseObject<Object>(moreInfo, errorCode);;
		String result = JSON.toJSONString(responseObject);
		String callback = req.getParameter("callback");
		if(StringUtils.isNotEmpty(callback)) {
			return callback+"("+result+")";
		}
		return result;
	}

	private BizException getBizException(Throwable e) {
		Throwable currentException = e;
		do {
			if (currentException instanceof BizException)
				return (BizException) currentException;
			e = currentException;
			currentException = e.getCause();
		} while (currentException != null && currentException != e);

		return null;
	}
}